package org.jsola.hr.service.impl;


import com.alibaba.fastjson.JSONObject;
import org.jsola.cache.ICache;
import org.jsola.hr.common.CacheKeyKit;
import org.jsola.hr.dto.SocAccountDTO;
import org.jsola.hr.entity.SocWebsiteDO;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.service.ISocCacheService;
import org.jsola.hr.service.ISocWebsiteService;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrConstants.*;

/**
 * 公司首页报名表
 *
 * @author zhr
 */
@Service("hrSocCacheServiceImpl")
public class SocCacheServiceImpl implements ISocCacheService {


    @Autowired
    private ICache cache;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Autowired
    private ISocWebsiteService socWebsiteService;

    @Override
    public void setSocAccountCache(SocAccountDTO socAccountDTO, TokenUser tokenUser) {
        // 前端传过来的 cookie 是 {"key":"value"} 形式,改成 key=value的形式
        if (!StringUtils.isEmpty(socAccountDTO.getCookie())) {
            JSONObject cookieJsonObject = JSONObject.parseObject(socAccountDTO.getCookie());
            StringBuilder cookies = new StringBuilder();
            for (String cookieKey : cookieJsonObject.keySet()) {
                cookies.append(cookieKey);
                cookies.append("=");
                cookies.append(cookieJsonObject.get(cookieKey));
                cookies.append(";");
            }
            socAccountDTO.setAreaName(adminProviderService.selectAreaById(socAccountDTO.getAreaId()));
            socAccountDTO.setCookie(cookies.toString());
        }
        // 匹配是哪一种社保类型
        switch (socAccountDTO.getAccountType()) {
            case SOC_CACHE:
                cache.set(CacheKeyKit.getSocAccount(tokenUser.getUserId(), socAccountDTO.getAreaId()), socAccountDTO, (30 * 60 * 1000));
                break;
            case ME_CACHE:
                cache.set(CacheKeyKit.getMeAccount(tokenUser.getUserId(), socAccountDTO.getAreaId()), socAccountDTO, (30 * 60 * 1000));
                break;
            case PF_CACHE:
                cache.set(CacheKeyKit.getPfAccount(tokenUser.getUserId(), socAccountDTO.getAreaId()), socAccountDTO, (30 * 60 * 1000));
                break;
            default:
        }
    }

    @Override
    public List<SocAccountDTO> getSocAccount(String areaId, TokenUser tokenUser) {
        Set<String> keys;
        List<SocAccountDTO> socAccountDTOList = new ArrayList<>();
        if (!StringUtils.isEmpty(areaId)) {
            keys = cache.keys("socCacheUser:" + tokenUser.getUserId() + "areaId" + areaId);
        } else {
            keys = cache.keys("socCacheUser:" + tokenUser.getUserId());
        }
        if (!CollectionUtils.isEmpty(keys)) {
            for (String key : keys) {
                SocAccountDTO socAccountDTO = cache.get(key);
                if (!ObjectUtils.isEmpty(socAccountDTO)) {
                    socAccountDTOList.add(socAccountDTO);
                }
            }
        }
        // 如果有传areaId要把 缺的类型补上并且赋值未登录
        if (!StringUtils.isEmpty(areaId)) {
            List<SocWebsiteDO> socWebsiteList = socWebsiteService.selectWebSiteByAreaId(areaId);
            Map<String, List<SocWebsiteDO>> socWebsiteListGroupAreaName =
                    socWebsiteList.stream().collect(Collectors.groupingBy(SocWebsiteDO::getType));
            List<String> accountTypeList = socAccountDTOList
                    .stream()
                    .map(SocAccountDTO::getAccountType)
                    .collect(Collectors.toList());
            socAccountDTOList.forEach(socAccountDTO -> {
                socAccountDTO.setIsLogin(true);
                socAccountDTO.setLoginUrl(socWebsiteListGroupAreaName.get(socAccountDTO.getAccountType()).get(0).getLoginUrl());
            });
            if (!accountTypeList.contains(SOC_CACHE)) {
                fillSocAccountDTO(socAccountDTOList, areaId, SOC_CACHE, socWebsiteListGroupAreaName);
            }
            if (!accountTypeList.contains(ME_CACHE)) {
                fillSocAccountDTO(socAccountDTOList, areaId, ME_CACHE, socWebsiteListGroupAreaName);
            }
            if (!accountTypeList.contains(PF_CACHE)) {
                fillSocAccountDTO(socAccountDTOList, areaId, PF_CACHE, socWebsiteListGroupAreaName);
            }
        }
        socAccountDTOList.sort(Comparator.comparing(SocAccountDTO::getAreaId).thenComparing(SocAccountDTO::getAccountType));
        return socAccountDTOList;
    }

    @Override
    public Boolean deceive(Boolean deceive) {
        if (deceive != null) {
            cache.set(CacheKeyKit.getSmallProgram(), deceive);
        }
        return cache.get(CacheKeyKit.getSmallProgram());
    }

    private void fillSocAccountDTO(List<SocAccountDTO> socAccountDTOList, String areaId, String accountType, Map<String, List<SocWebsiteDO>> socWebsiteListGroupAreaName) {
        SocAccountDTO socAccountDTO = new SocAccountDTO();
        socAccountDTO.setIsLogin(false);
        socAccountDTO.setAccountType(accountType);
        socAccountDTO.setAreaId(areaId);
        socAccountDTO.setLoginUrl(socWebsiteListGroupAreaName.get(accountType).get(0).getLoginUrl());
        socAccountDTOList.add(socAccountDTO);
    }
}
